/*-------------------------------------------------------------------------
*
* pthread-win32.c
*	 partial pthread implementation for win32
*
* Copyright (c) 2004-2022, PostgreSQL Global Development Group
* IDENTIFICATION
*	src/interfaces/libpq/pthread-win32.c
*
*-------------------------------------------------------------------------
*/

#include "postgres_fe.h"

#include "pthread-win32.h"

DWORD pthread_self(void)
{
	return GetCurrentThreadId();
}

void pthread_setspecific(pthread_key_t fc_key, void *fc_val)
{
}

void * pthread_getspecific(pthread_key_t fc_key)
{
	return NULL;
}

int pthread_mutex_init(pthread_mutex_t *fc_mp, void *fc_attr)
{
	fc_mp->initstate = 0;
	return 0;
}

int pthread_mutex_lock(pthread_mutex_t *fc_mp)
{
	/* 如果尚未完成，则初始化csection */
	if (fc_mp->initstate != 1)
	{
		LONG		istate;

		while ((istate = InterlockedExchange(&fc_mp->initstate, 2)) == 2)
			Sleep(0);			/* 等待，另一个线程正在进行此操作 */
		if (istate != 1)
			InitializeCriticalSection(&fc_mp->csection);
		InterlockedExchange(&fc_mp->initstate, 1);
	}
	EnterCriticalSection(&fc_mp->csection);
	return 0;
}

int pthread_mutex_unlock(pthread_mutex_t *fc_mp)
{
	if (fc_mp->initstate != 1)
		return EINVAL;
	LeaveCriticalSection(&fc_mp->csection);
	return 0;
}
